import Search from "@/components/public/Search";
import { View, Text, Image } from "@tarojs/components";
import ico_del from "@/assets/image/ico_del.svg";
import "./index.scss";
import { getStoreViewCount } from "@/services/entities/all";
import { useEffect, useRef, useState } from "react";
import { useReachBottom } from "@tarojs/taro";
import Taro from "@tarojs/taro";
import { linkWithParams } from "@/helper/utils";
import { routes } from "@/constants/routes";
import { AtDrawer } from "taro-ui";
const SearchPage = () => {
  const [list, setList] = useState<any>([]);
  const [searchList, setSearchList] = useState<any>([]);
  const [page, setPage] = useState(1);
  const level = useRef<any>("");
  const [showLevel, setShowLevel] = useState(false);
  const levelList = [
    { label: "全部", value: "" },
    { label: "优质商家", value: 4 },
    { label: "荣誉商家", value: 3 },
    { label: "普通商家", value: 2 },
    { label: "二级商家", value: 1 },
  ];
  const time = useRef<any>({ start: void 0, end: void 0 });
  const [text, setText] = useState({ time: '今日访问', call: '进入拨打' })
  const [showTime, setShowTime] = useState(false);
  var nowTime = new Date().getTime();
  var dayTime = 24 * 60 * 60 * 1000;
  const timeList = [
    { label: "全部", value: { start: void 0, end: void 0 } },
    {
      label: "一周",
      value: {
        start: new Date(nowTime - 7 * dayTime),
        end: new Date(nowTime),
      },
    },
    {
      label: "一个月",
      value: {
        start: new Date(nowTime - 30 * dayTime),
        end: new Date(nowTime),
      },
    },
    {
      label: "三个月",
      value: {
        start: new Date(nowTime - 90 * dayTime),
        end: new Date(nowTime),
      },
    },
    {
      label: "半年",
      value: {
        start: new Date(nowTime - 180 * dayTime),
        end: new Date(nowTime),
      },
    },
  ];

  const onCloseLevel = () => {
    setShowLevel(false);
  };
  const onCloseTime = () => {
    setShowTime(false);
  };
  const currentValue = useRef("");
  const getList = (pageNum) => {
    getStoreViewCount({
      currentPage: pageNum,
      pageSize: 10,
      name: currentValue.current,
      level: level.current,
      startTime: time.current.start,
      endTime: time.current.end,
    }).then((res: any) => {
      if (pageNum === 1) {
        setList(res.records);
      } else {
        setList((old) => {
          return [...old, ...res.records];
        });
      }
    });
  };

  const getFirstPage = () => {
    if (page === 1) {
      getList(1);
    } else {
      setPage(1);
    }
  };

  const setLocal = (value) => {
    const local = Taro.getStorageSync("searchList");
    let result = "";
    let arr: any = [];
    if (local) {
      arr = local.split(",");
      if (arr.length > 9) {
        arr.pop();
        arr.push(value);
      } else {
        arr.push(value);
      }
    } else {
      arr.push(value);
    }
    result = arr.join(",");
    setSearchList(arr);
    Taro.setStorageSync("searchList", result);
  };

  const clear = () => {
    Taro.setStorageSync("searchList", "");
    setSearchList([]);
  };

  const setTextByTime = (idx: number) => {
    switch (idx) {
      case 0:
        setText({ time: '今日访问', call: '进入拨打' })
        break;
      case 1:
        setText({ time: '本周访问', call: '本周拨打' })
        break;
      case 2:
        setText({ time: '本月访问', call: '本月拨打' })
        break;
      case 3:
        setText({ time: '三月访问', call: '三月拨打' })
        break;
      case 4:
        setText({ time: '半年访问', call: '半年拨打' })
        break;
      default:
        break;
    }
  }

  useEffect(() => {
    const local = Taro.getStorageSync("searchList");
    let arr: any = [];
    if (local) {
      arr = local.split(",");
      setSearchList(arr);
    }
  }, []);

  useEffect(() => {
    if (page) {
      getList(page);
    }
  }, [page]);

  useReachBottom(() => {
    if (page * 10 === list.length) {
      setPage((old) => old + 1);
    }
  });

  return (
    <View className="search-container bg-page">
      <View className="dis-flex bg-ffffff pd-18 border-box">
        <Search
          className="bg-ffffff width-full"
          value={currentValue.current}
          onInput={(value) => {
            currentValue.current = value;
          }}
          right={
            <View
              className="bg-394B5D cl-white fs-28 lh-38 pd-tb-8 border-box pd-lr-38 br-28 mr-4"
              onClick={() => {
                getFirstPage();
                if (currentValue.current) {
                  setLocal(currentValue.current);
                }
              }}
            >
              搜索
            </View>
          }
        />
      </View>
      <AtDrawer
        show={showLevel}
        onClose={onCloseLevel}
        onItemClick={(idx) => {
          onCloseLevel();
          level.current = levelList[idx].value;
          getFirstPage();
        }}
        mask
        items={levelList.map((item) => item.label)}
      ></AtDrawer>
      <AtDrawer
        show={showTime}
        onClose={onCloseTime}
        onItemClick={(idx) => {
          onCloseTime();
          time.current = timeList[idx].value;
          getFirstPage();
          setTextByTime(idx)
        }}
        mask
        items={timeList.map((item) => item.label)}
      ></AtDrawer>
      <View className="dis-flex">
        <View
          className="flex-1 dis-flex flex-center mg-16 mb-2 bg-394B5D cl-white fs-32 pd-tb-12 br-28"
          onClick={() => {
            setShowLevel(true);
          }}
        >
          商家等级
        </View>
        <View
          className="ml-20 flex-1 dis-flex flex-center mg-16 mb-2 bg-394B5D cl-white fs-32 pd-tb-12 br-28"
          onClick={() => {
            setShowTime(true);
          }}
        >
          时间
        </View>
      </View>
      <View className="dis-flex align-center justify-between mt-32 pd-lr-18 border-box">
        <Text className="fs-32 cl-black">历史记录</Text>
        <View className="dis-flex align-center" onClick={clear}>
          <Image src={ico_del} className="mr-8 img-36" />
          <Text className="fs-28 cl-848484">删除</Text>
        </View>
      </View>
      <View className="dis-flex flex-wrap gap-16 pt-32 pd-lr-18 border-box">
        {searchList.map((item, index) => {
          return (
            <View
              onClick={() => {
                currentValue.current = item;
                getList(1);
                setPage(1);
              }}
              key={index}
              className="pd-lr-18 pd-tb-12 fs-24 lh-24 cl-black bg-ffffff br-8"
            >
              {item}
            </View>
          );
        })}
      </View>
      <View className="flex-column mt-32 pd-lr-18 border-box">
        {list?.map((item, index) => {
          return (
            <View
              key={index}
              className="flex-column mb-12 bg-ffffff dis-flex br-8 pd-12 border-box"
            >
              <View className="dis-flex justify-center">
                <Text
                  className="fs-32 lh-42 cl-black"
                  onClick={() => {
                    linkWithParams(routes.ROUTES_SHOP_DETAIL, {
                      storeId: item.id,
                    });
                  }}
                >
                  {item.storeName}
                </Text>
              </View>
              <View className="dis-flex justify-evenly width-100 mt-20">
                <View className="flex-column align-center">
                  <Text className="fs-32 fw-600">{text.time}</Text>
                  <Text className="fs-48 fw-600">{item.todayCount}</Text>
                </View>
                <View className="flex-column align-center">
                  <Text className="fs-32 fw-600">{text.call}</Text>
                  <Text className="fs-48 fw-600">{item.todayCallCount}</Text>
                </View>
                <View className="flex-column align-center">
                  <Text className="fs-32 fw-600">历史访问</Text>
                  <Text className="fs-48 fw-600">{item.allCount}</Text>
                </View>
              </View>
            </View>
          );
        })}
      </View>
    </View>
  );
};

export default SearchPage;
